import express from 'express';
import axios from 'axios';

const router = express.Router();

// 管理端API基础URL
const ADMIN_API_BASE = 'http://localhost:3000/api';

// 获取博客分类和栏目
router.get('/categories', async (req, res) => {
    try {
        // 从管理端API获取博客分类
        const [categoriesResponse, columnsResponse] = await Promise.all([
            axios.get(`${ADMIN_API_BASE}/blog-categories`),
            axios.get(`${ADMIN_API_BASE}/blog-columns`)
        ]);

        const categories = categoriesResponse.data.success ? categoriesResponse.data.data.categories || [] : [];
        const columns = columnsResponse.data.success ? columnsResponse.data.data.columns || [] : [];

        res.json({
            success: true,
            data: {
                categories: categories,
                columns: columns
            }
        });
        
    } catch (error) {
        console.error('获取博客分类失败:', error);
        // 返回默认分类作为fallback
        res.json({
            success: true,
            data: {
                categories: [
                    { id: 1, name: '骑行技巧', description: '骑行技巧和教程' },
                    { id: 2, name: '产品评测', description: '自行车产品评测' },
                    { id: 3, name: '保养知识', description: '自行车保养维护' },
                    { id: 4, name: '行业资讯', description: '自行车行业动态' }
                ],
                columns: [
                    { id: 1, name: '技术专栏', description: '专业技术文章' },
                    { id: 2, name: '用户分享', description: '用户经验分享' }
                ]
            }
        });
    }
});

// 博客文章列表
router.get('/posts', async (req, res) => {
    try {
        const { category, column, page = 1, limit = 10, search = '' } = req.query;
        
        // 构建查询参数
        const params = {
            status: 'published',
            page: parseInt(page),
            limit: parseInt(limit)
        };
        
        if (category) params.category_id = category;
        if (column) params.column_id = column;
        if (search) params.search = search;

        // 从管理端API获取已发布的文章
        const response = await axios.get(`${ADMIN_API_BASE}/articles`, { params });

        if (response.data.success) {
            const articles = response.data.data.articles || [];
            
            // 转换数据格式以匹配用户端期望的格式
            const posts = articles.map(article => ({
                id: article.id,
                title: article.title,
                content: article.content,
                excerpt: article.excerpt || article.content.substring(0, 200) + '...',
                author: article.author_name || '管理员',
                created_at: article.created_at,
                updated_at: article.updated_at,
                category: article.category_name || article.category || '默认分类',
                category_id: article.category_id,
                column: article.column_name || '',
                column_id: article.column_id,
                views: article.views || 0,
                likes: article.likes || 0,
                comments: article.comments || 0,
                featured: article.featured || false,
                cover_image: article.cover_image || ''
            }));

            res.json({
                success: true,
                data: {
                    posts: posts,
                    total: response.data.data.total || posts.length,
                    page: response.data.data.page || 1,
                    limit: response.data.data.limit || 10,
                    totalPages: response.data.data.totalPages || 1
                }
            });
        } else {
            // 如果API调用失败，返回模拟数据作为fallback
            const fallbackPosts = [
                {
                    id: 1,
                    title: '欢迎来到我们的博客',
                    content: '这是我们的第一篇博客文章...',
                    author: '管理员',
                    created_at: new Date().toISOString(),
                    category: '公告',
                    views: 2450,
                    likes: 156,
                    comments: 42,
                    featured: true
                },
                {
                    id: 2,
                    title: '自行车保养指南',
                    content: '学习如何正确保养您的自行车...',
                    author: '技术专家',
                    created_at: new Date(Date.now() - 86400000).toISOString(),
                    category: '教程',
                    views: 1890,
                    likes: 98,
                    comments: 28,
                    featured: false
                }
            ];

            res.json({
                success: true,
                data: fallbackPosts,
                total: fallbackPosts.length,
                page: 1,
                limit: 10,
                totalPages: 1
            });
        }
    } catch (error) {
        console.error('获取博客文章失败:', error);
        
        // 返回模拟数据作为fallback
        const fallbackPosts = [
            {
                id: 1,
                title: '欢迎来到我们的博客',
                content: '这是我们的第一篇博客文章...',
                author: '管理员',
                created_at: new Date().toISOString(),
                category: '公告',
                views: 2450,
                likes: 156,
                comments: 42,
                featured: true
            },
            {
                id: 2,
                title: '自行车保养指南',
                content: '学习如何正确保养您的自行车...',
                author: '技术专家',
                created_at: new Date(Date.now() - 86400000).toISOString(),
                category: '教程',
                views: 1890,
                likes: 98,
                comments: 28,
                featured: false
            }
        ];

        res.json({
            success: true,
            data: fallbackPosts,
            total: fallbackPosts.length,
            page: 1,
            limit: 10,
            totalPages: 1
        });
    }
});

// 获取单个博客文章
router.get('/posts/:id', async (req, res) => {
    try {
        const postId = parseInt(req.params.id);
        
        // 从管理端API获取单个文章
        const response = await axios.get(`${ADMIN_API_BASE}/articles/${postId}`);

        if (response.data.success) {
            const article = response.data.data;
            
            // 转换数据格式
            const post = {
                id: article.id,
                title: article.title,
                content: article.content,
                author: article.author_name || '管理员',
                created_at: article.created_at,
                category: article.category || '默认分类',
                views: article.views || 0,
                likes: article.likes || 0,
                comments: article.comments || 0,
                featured: article.featured || false
            };

            res.json({
                success: true,
                data: post
            });
        } else {
            // 如果API调用失败，返回模拟数据
            const fallbackPost = {
                id: postId,
                title: `博客文章 ${postId}`,
                content: `这是博客文章 ${postId} 的详细内容...`,
                author: '作者',
                created_at: new Date().toISOString(),
                category: '默认分类',
                views: 1000,
                likes: 50,
                comments: 10,
                featured: false
            };

            res.json({
                success: true,
                data: fallbackPost
            });
        }
    } catch (error) {
        console.error('获取博客文章失败:', error);
        
        // 返回模拟数据作为fallback
        const fallbackPost = {
            id: parseInt(req.params.id),
            title: `博客文章 ${req.params.id}`,
            content: `这是博客文章 ${req.params.id} 的详细内容...`,
            author: '作者',
            created_at: new Date().toISOString(),
            category: '默认分类',
            views: 1000,
            likes: 50,
            comments: 10,
            featured: false
        };

        res.json({
            success: true,
            data: fallbackPost
        });
    }
});

// 博客分类
router.get('/categories', async (req, res) => {
    try {
        // 从管理端API获取分类
        const response = await axios.get(`${ADMIN_API_BASE}/blog-categories`);

        if (response.data.success) {
            const categories = response.data.data.categories || [];
            
            // 转换数据格式
            const formattedCategories = categories.map(category => ({
                id: category.id,
                name: category.name,
                slug: category.slug,
                count: category.article_count || 0,
                description: category.description || ''
            }));

            res.json({
                success: true,
                data: formattedCategories
            });
        } else {
            // 如果API调用失败，返回模拟数据
            const fallbackCategories = [
                { id: 1, name: '公告', slug: 'announcements', count: 5, description: '系统公告和重要通知' },
                { id: 2, name: '教程', slug: 'tutorials', count: 8, description: '自行车使用和保养教程' },
                { id: 3, name: '新闻', slug: 'news', count: 3, description: '行业新闻和动态' },
                { id: 4, name: '活动', slug: 'events', count: 2, description: '促销活动和用户活动' }
            ];

            res.json({
                success: true,
                data: fallbackCategories
            });
        }
    } catch (error) {
        console.error('获取分类失败:', error);
        
        // 返回模拟数据作为fallback
        const fallbackCategories = [
            { id: 1, name: '公告', slug: 'announcements', count: 5, description: '系统公告和重要通知' },
            { id: 2, name: '教程', slug: 'tutorials', count: 8, description: '自行车使用和保养教程' },
            { id: 3, name: '新闻', slug: 'news', count: 3, description: '行业新闻和动态' },
            { id: 4, name: '活动', slug: 'events', count: 2, description: '促销活动和用户活动' }
        ];

        res.json({
            success: true,
            data: fallbackCategories
        });
    }
});

// 搜索博客文章
router.get('/posts/search', async (req, res) => {
    try {
        const query = req.query.q;
        
        if (!query || query.trim() === '') {
            return res.status(400).json({
                success: false,
                message: '搜索关键词不能为空'
            });
        }

        // 从管理端API搜索文章
        const response = await axios.get(`${ADMIN_API_BASE}/articles/search`, {
            params: {
                q: query,
                page: req.query.page || 1,
                limit: req.query.limit || 10
            }
        });

        if (response.data.success) {
            const articles = response.data.data.articles || [];
            
            // 转换数据格式
            const posts = articles.map(article => ({
                id: article.id,
                title: article.title,
                content: article.content,
                author: article.author_name || '管理员',
                created_at: article.created_at,
                category: article.category || '默认分类',
                views: article.views || 0,
                likes: article.likes || 0,
                comments: article.comments || 0,
                featured: article.featured || false
            }));

            res.json({
                success: true,
                data: posts,
                total: response.data.data.total || posts.length,
                page: response.data.data.page || 1,
                limit: response.data.data.limit || 10,
                totalPages: response.data.data.totalPages || 1
            });
        } else {
            res.json({
                success: true,
                data: [],
                total: 0,
                page: 1,
                limit: 10,
                totalPages: 0
            });
        }
    } catch (error) {
        console.error('搜索博客文章失败:', error);
        res.json({
            success: true,
            data: [],
            total: 0,
            page: 1,
            limit: 10,
            totalPages: 0
        });
    }
});

// 获取热门文章（按浏览量排序）
router.get('/posts/popular', async (req, res) => {
    try {
        // 从管理端API获取文章并按浏览量排序
        const response = await axios.get(`${ADMIN_API_BASE}/articles`, {
            params: {
                status: 'published',
                limit: req.query.limit || 5
            }
        });

        if (response.data.success) {
            const articles = response.data.data.articles || [];
            
            // 按浏览量排序
            const popularArticles = articles
                .sort((a, b) => (b.views || 0) - (a.views || 0))
                .slice(0, req.query.limit || 5);
            
            // 转换数据格式
            const posts = popularArticles.map(article => ({
                id: article.id,
                title: article.title,
                content: article.content,
                author: article.author_name || '管理员',
                created_at: article.created_at,
                category: article.category || '默认分类',
                views: article.views || 0,
                likes: article.likes || 0,
                comments: article.comments || 0,
                featured: article.featured || false
            }));

            res.json({
                success: true,
                data: posts
            });
        } else {
            // 返回模拟的热门文章
            const fallbackPopular = [
                {
                    id: 1,
                    title: '2025年自行车行业发展趋势分析',
                    content: '随着环保意识的提升和健康生活方式的流行...',
                    author: '张明',
                    created_at: new Date().toISOString(),
                    category: '市场趋势',
                    views: 2450,
                    likes: 156,
                    comments: 42,
                    featured: true
                },
                {
                    id: 2,
                    title: '山地自行车保养维护全攻略',
                    content: '从链条清洁到刹车调整...',
                    author: '王强',
                    created_at: new Date(Date.now() - 86400000).toISOString(),
                    category: '保养维修',
                    views: 3120,
                    likes: 210,
                    comments: 65,
                    featured: true
                }
            ];

            res.json({
                success: true,
                data: fallbackPopular
            });
        }
    } catch (error) {
        console.error('获取热门文章失败:', error);
        
        // 返回模拟的热门文章
        const fallbackPopular = [
            {
                id: 1,
                title: '2025年自行车行业发展趋势分析',
                content: '随着环保意识的提升和健康生活方式的流行...',
                author: '张明',
                created_at: new Date().toISOString(),
                category: '市场趋势',
                views: 2450,
                likes: 156,
                comments: 42,
                featured: true
            },
            {
                id: 2,
                title: '山地自行车保养维护全攻略',
                content: '从链条清洁到刹车调整...',
                author: '王强',
                created_at: new Date(Date.now() - 86400000).toISOString(),
                category: '保养维修',
                views: 3120,
                likes: 210,
                comments: 65,
                featured: true
            }
        ];

        res.json({
            success: true,
            data: fallbackPopular
        });
    }
});

export default router;